//
//  GSAdManager.m
//  GameSky
//
//  Created by lanou on 16/1/22.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSAdManager.h"

#define kCachedCurrentImage ([[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingString:@"/adcurrent.png"])
#define kCachedNewImage     ([[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingString:@"/adnew.png"])

#define kURL @"http://appapi2.gamersky.com/v2/adstart"

@interface GSAdManager ()

@property (nonatomic, strong)GSStartADModel *model;

@end

@implementation GSAdManager

+ (GSAdManager *)shareManager
{
    static GSAdManager *adM = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        adM = [[GSAdManager alloc]init];
    });
    return adM;
}

+ (BOOL)isShouldDisplayAd
{
    // 从缓存文件夹中取图片,有图片则可以展示
    return ([[NSFileManager defaultManager]fileExistsAtPath:kCachedCurrentImage isDirectory:NULL] || [[NSFileManager defaultManager]fileExistsAtPath:kCachedNewImage isDirectory:NULL]);
}

+ (UIImage *)getAdImage
{
    /**
     *  如果有新的图片,则移除老的图片
     */
    if ([[NSFileManager defaultManager]fileExistsAtPath:kCachedNewImage isDirectory:NULL]) {
        // 移除当前图片
        [[NSFileManager defaultManager]removeItemAtPath:kCachedCurrentImage error:nil];
        // 把新的图片替换成当前图片
        [[NSFileManager defaultManager]moveItemAtPath:kCachedNewImage toPath:kCachedCurrentImage error:nil];
    }
    
    /**
     *  返回当前图片
     */
    return [UIImage imageWithData:[NSData dataWithContentsOfFile:kCachedCurrentImage]];
}

- (void)downloadImage:(NSString *)imageUrl
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString: imageUrl]];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (data) {
            
            [data writeToFile:kCachedNewImage atomically:YES];
            
        }

    }];
    
    [task resume];
    
}

- (GSStartADModel *)loadLatestAdImage
{
    NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
    paraDict[@"deviceType"] = @"iPhone5,3";
    paraDict[@"deviceId"] = @"17E14E61-4069-4736-992D-EE596A7AECBC";
    paraDict[@"os"] = @"iOS";
    paraDict[@"osVersion"] = @"8.4";
    paraDict[@"app"] = @"GSApp";
    paraDict[@"appVersion"] = @"2.1.0";
    paraDict[@"request"] = @{};
    
    [GSNetworkManager requestWithUrlStr:kURL paraDict:paraDict method:POST success:^(NSURLResponse *response, NSData *data) {
    
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *array = dic[@"result"];
        
        
        for (NSDictionary *oneDic in array) {
            
            self.model = [[GSStartADModel alloc]init];

            
            [self.model setValuesForKeysWithDictionary:oneDic];
            
            [self downloadImage:self.model.picAdress];
            
        }

    } failure:^(NSError *error) {
        
        NSLog(@"%@",error);
        
    }];
    
    return self.model;
    
}

@end
